<template>
  <view class="material-manager">
    <!-- 头部操作栏 -->
    <view class="header-actions">
      <view class="search-bar">
        <input 
          class="search-input"
          v-model="searchKeyword"
          placeholder="搜索物料编码或名称"
          @confirm="searchMaterials"
        />
        <button class="search-btn" @click="searchMaterials">
          <text class="icon">🔍</text>
        </button>
      </view>
      <button class="add-btn" @click="addNewMaterial">
        <text class="icon">+</text>
        <text>添加</text>
      </button>
    </view>

    <!-- 物料列表 -->
    <scroll-view class="material-list" scroll-y>
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="materials.length === 0" class="empty-state">
        <view class="empty-icon">📦</view>
        <text class="empty-title">暂无物料</text>
        <text class="empty-desc">点击右上角添加物料</text>
      </view>

      <view v-else>
        <view 
          class="material-item"
          v-for="(material, index) in materials"
          :key="material.id"
          :class="{ selected: isSelected(material) }"
          @click="selectMaterial(material, index)"
        >
          <view class="item-main">
            <view class="item-header">
              <text class="material-code">{{ material.code }}</text>
              <view class="item-actions">
                <button 
                  class="action-btn edit" 
                  @click.stop="editMaterial(material)"
                >
                  <text class="icon">✏️</text>
                </button>
                <button 
                  class="action-btn delete" 
                  @click.stop="deleteMaterial(material)"
                >
                  <text class="icon">🗑️</text>
                </button>
              </view>
            </view>
            
            <view class="item-content">
              <text class="material-name">{{ material.name }}</text>
              <text class="material-spec">{{ material.spec }}</text>
            </view>
            
            <view class="item-stats">
              <view class="stat">
                <text class="stat-label">数量:</text>
                <text class="stat-value">{{ material.quantity }}件</text>
              </view>
              <view class="stat">
                <text class="stat-label">重量:</text>
                <text class="stat-value">{{ material.weight }}kg</text>
              </view>
              <view class="stat">
                <text class="stat-label">库位:</text>
                <text class="stat-value">{{ material.location || '未指定' }}</text>
              </view>
            </view>
          </view>
          
          <!-- 编辑模式 -->
          <view v-if="editingIndex === index" class="edit-form">
            <view class="form-grid">
              <view class="form-group">
                <text class="label">物料编码</text>
                <input 
                  class="input" 
                  v-model="editForm.code" 
                  placeholder="请输入物料编码"
                />
              </view>
              <view class="form-group">
                <text class="label">物料名称</text>
                <input 
                  class="input" 
                  v-model="editForm.name" 
                  placeholder="请输入物料名称"
                />
              </view>
            </view>
            
            <view class="form-grid">
              <view class="form-group">
                <text class="label">规格型号</text>
                <input 
                  class="input" 
                  v-model="editForm.spec" 
                  placeholder="请输入规格型号"
                />
              </view>
              <view class="form-group">
                <text class="label">批次号</text>
                <input 
                  class="input" 
                  v-model="editForm.batchNo" 
                  placeholder="请输入批次号"
                />
              </view>
            </view>
            
            <view class="form-grid">
              <view class="form-group">
                <text class="label">数量</text>
                <input 
                  class="input" 
                  v-model.number="editForm.quantity" 
                  type="number"
                  placeholder="0"
                  min="0"
                />
              </view>
              <view class="form-group">
                <text class="label">重量(kg)</text>
                <input 
                  class="input" 
                  v-model.number="editForm.weight" 
                  type="digit"
                  placeholder="0.00"
                  min="0"
                  step="0.01"
                />
              </view>
            </view>
            
            <view class="form-group">
              <text class="label">库位</text>
              <input 
                class="input" 
                v-model="editForm.location" 
                placeholder="请输入库位"
              />
            </view>
            
            <view class="form-actions">
              <button class="btn btn-secondary" @click="cancelEdit">取消</button>
              <button class="btn btn-primary" @click="saveEdit">保存</button>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部统计 -->
    <view class="footer-stats">
      <view class="stat-item">
        <text class="stat-label">总计:</text>
        <text class="stat-value">{{ totalQuantity }}件 / {{ totalWeight }}kg</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">已选:</text>
        <text class="stat-value">{{ selectedCount }}件</text>
      </view>
    </view>
  </view>
</template>

<script lang="js" setup>
// 在uni-app中，Composition API是全局可用的，不需要导入
// 类型导入在JS中不需要，直接使用对象结构

// Props定义 - 使用普通对象方式
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  readonly: {
    type: Boolean,
    default: false
  },
  allowSelection: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: true
  }
})

// Emits定义 - 使用数组方式
const emit = defineEmits([
  'update:modelValue',
  'material-selected',
  'material-updated',
  'material-deleted',
  'material-added'
])

// 响应式数据
const materials = ref([...props.modelValue])
const searchKeyword = ref('')
const loading = ref(false)
const editingIndex = ref(-1)
const selectedMaterials = ref([])

const editForm = ref({
  id: '',
  code: '',
  name: '',
  spec: '',
  quantity: 0,
  weight: 0,
  location: '',
  batchNo: ''
})

// 计算属性
const totalQuantity = computed(() =>
  materials.value.reduce((sum, item) => sum + (item.quantity || 0), 0)
)

const totalWeight = computed(() =>
  materials.value.reduce((sum, item) => sum + (item.weight || 0), 0)
)

const selectedCount = computed(() => selectedMaterials.value.length)

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  materials.value = [...newValue]
}, { deep: true })

// 监听内部数据变化
watch(materials, (newValue) => {
  emit('update:modelValue', newValue)
}, { deep: true })

// 方法
const searchMaterials = () => {
  // 实现搜索逻辑
  console.log('搜索物料:', searchKeyword.value)
}

const addNewMaterial = () => {
  const newMaterial = {
    id: `MAT${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
    code: '',
    name: '',
    spec: '',
    quantity: 0,
    weight: 0,
    location: '',
    batchNo: ''
  }
  
  materials.value.unshift(newMaterial)
  editMaterial(newMaterial, 0)
}

const selectMaterial = (material, index) => {
  if (!props.allowSelection) return
  
  if (props.multiple) {
    const existingIndex = selectedMaterials.value.findIndex(m => m.id === material.id)
    if (existingIndex >= 0) {
      selectedMaterials.value.splice(existingIndex, 1)
    } else {
      selectedMaterials.value.push(material)
    }
  } else {
    selectedMaterials.value = [material]
    emit('material-selected', material)
  }
}

const isSelected = (material) => {
  return selectedMaterials.value.some(m => m.id === material.id)
}

const editMaterial = (material, index) => {
  if (props.readonly) return
  
  editingIndex.value = index
  editForm.value = { ...material }
}

const cancelEdit = () => {
  editingIndex.value = -1
  editForm.value = {
    id: '',
    code: '',
    name: '',
    spec: '',
    quantity: 0,
    weight: 0,
    location: '',
    batchNo: ''
  }
}

const saveEdit = () => {
  if (editingIndex.value >= 0) {
    const updatedMaterial = { ...editForm.value }
    materials.value[editingIndex.value] = updatedMaterial
    emit('material-updated', updatedMaterial, editingIndex.value)
    cancelEdit()
  }
}

const deleteMaterial = (material) => {
  if (props.readonly) return
  
  uni.showModal({
    title: '确认删除',
    content: `确定要删除物料 "${material.name}" 吗？`,
    success: (res) => {
      if (res.confirm) {
        const index = materials.value.findIndex(m => m.id === material.id)
        if (index >= 0) {
          const deletedMaterial = materials.value.splice(index, 1)[0]
          emit('material-deleted', deletedMaterial, index)
        }
      }
    }
  })
}

const validateMaterial = (material) => {
  if (!material.code?.trim()) {
    uni.showToast({ title: '物料编码不能为空', icon: 'error' })
    return false
  }
  if (!material.name?.trim()) {
    uni.showToast({ title: '物料名称不能为空', icon: 'error' })
    return false
  }
  if (!material.spec?.trim()) {
    uni.showToast({ title: '规格型号不能为空', icon: 'error' })
    return false
  }
  if (!material.quantity || material.quantity <= 0) {
    uni.showToast({ title: '数量必须大于0', icon: 'error' })
    return false
  }
  if (!material.weight || material.weight <= 0) {
    uni.showToast({ title: '重量必须大于0', icon: 'error' })
    return false
  }
  return true
}

// 暴露方法
const getSelectedMaterials = () => {
  return [...selectedMaterials.value]
}

const clearSelection = () => {
  selectedMaterials.value = []
}

// 暴露给父组件的方法
defineExpose({
  getSelectedMaterials,
  clearSelection,
  addNewMaterial,
  validateMaterial
})

// 生命周期
onMounted(() => {
  // 初始化
})
</script>

<style lang="scss" scoped>
.material-manager {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header-actions {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  border-bottom: 1rpx solid #E5E5E5;
  
  .search-bar {
    flex: 1;
    display: flex;
    align-items: center;
    background: #F5F5F5;
    border-radius: 24rpx;
    padding: 0 20rpx;
    
    .search-input {
      flex: 1;
      height: 60rpx;
      border: none;
      background: transparent;
      font-size: 28rpx;
    }
    
    .search-btn {
      background: transparent;
      border: none;
      padding: 10rpx;
      
      .icon {
        font-size: 32rpx;
      }
    }
  }
  
  .add-btn {
    display: flex;
    align-items: center;
    background: #007AFF;
    color: white;
    border-radius: 24rpx;
    padding: 16rpx 24rpx;
    font-size: 28rpx;
    
    .icon {
      margin-right: 8rpx;
    }
  }
}

.material-list {
  flex: 1;
  padding: 20rpx;
}

.loading-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
  
  .loading-text, .empty-title {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 12rpx;
  }
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
    color: #999;
  }
  
  .empty-desc {
    font-size: 28rpx;
    color: #999;
  }
}

.material-item {
  background: white;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  border: 1rpx solid #E5E5E5;
  
  &.selected {
    border-color: #007AFF;
    background: #F0F7FF;
  }
  
  .item-main {
    padding: 24rpx;
  }
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    
    .material-code {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .item-actions {
      display: flex;
      gap: 16rpx;
      
      .action-btn {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        
        &.edit {
          background: #E3F2FD;
          color: #2196F3;
        }
        
        &.delete {
          background: #FFEBEE;
          color: #F44336;
        }
      }
    }
  }
  
  .item-content {
    margin-bottom: 16rpx;
    
    .material-name {
      display: block;
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .material-spec {
      display: block;
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .item-stats {
    display: flex;
    gap: 30rpx;
    
    .stat {
      display: flex;
      align-items: center;
      gap: 8rpx;
      
      .stat-label {
        font-size: 24rpx;
        color: #999;
      }
      
      .stat-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .edit-form {
    padding: 24rpx;
    border-top: 1rpx solid #E5E5E5;
    background: #F9F9F9;
    
    .form-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20rpx;
      margin-bottom: 20rpx;
      
      .form-group {
        .label {
          display: block;
          font-size: 24rpx;
          color: #666;
          margin-bottom: 8rpx;
        }
        
        .input {
          width: 100%;
          height: 64rpx;
          border: 1rpx solid #DDD;
          border-radius: 8rpx;
          padding: 0 16rpx;
          font-size: 28rpx;
        }
      }
    }
    
    .form-actions {
      display: flex;
      gap: 20rpx;
      justify-content: flex-end;
      
      .btn {
        padding: 16rpx 32rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        
        &.btn-secondary {
          background: #F5F5F5;
          color: #666;
        }
        
        &.btn-primary {
          background: #007AFF;
          color: white;
        }
      }
    }
  }
}

.footer-stats {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  background: #F5F5F5;
  border-top: 1rpx solid #E5E5E5;
  
  .stat-item {
    display: flex;
    align-items: center;
    gap: 8rpx;
    
    .stat-label {
      font-size: 24rpx;
      color: #666;
    }
    
    .stat-value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}
</style>